<template>
    <el-form label-width="100px">
        <el-form-item label="SPU名称">
            <el-input placeholder="请您输入SPU名称" v-model="SpuParams.spuName"></el-input>
        </el-form-item>
        <el-form-item label="SPU品牌">
            <el-select v-model="SpuParams.tmId">
                <el-option v-for="item in allTradeMark" :key="item.id" :label="item.tmName" :value="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input v-model="SpuParams.description" type="textarea" placeholder="请您输入SPU描述"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
            <el-upload v-model:file-list="imgList" action="/api/admin/product/fileUpload" list-type="picture-card"
                :on-preview="handlePictureCardPreview">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%;" />
            </el-dialog>
        </el-form-item>
        <el-form-item label="SPU销售属性">
            <el-select v-model="saleAttrAndValueName"
                :placeholder="unSelectSaleAttr.length ? `还未选择${unSelectSaleAttr.length}个` : '无'">
                <el-option :value="`${item.id}:${item.name}`" v-for="item in unSelectSaleAttr" :label="item.name"
                    :key="item.id"></el-option>
            </el-select>
            <el-button :disabled="saleAttrAndValueName ? false : true" style="margin-left: 10px;" type="primary"
                size="default" icon="Plus" @click="addSaleAttr">添加属性</el-button>
            <el-table border style="margin: 10px 0px;" :data="saleAttr">
                <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                <el-table-column label="销售属性名字" width="120px" prop="saleAttrName"></el-table-column>
                <el-table-column label="销售属性值">
                    <template #="{ row, $index }">
                        <el-tag @close="row.spuSaleAttrValueList.splice($index, 1)" style="margin: 0px 5px;"
                            v-for="tag in row.spuSaleAttrValueList" :key="tag.id" class="mx-1" closable>
                            {{ tag.saleAttrValueName }}
                        </el-tag>
                        <el-input @blur="toLook(row)" v-model="row.saleAttrValue" v-if="row.flag == true" size="small"
                            style="width: 100px;" placeholder="请您输入属性值"></el-input>

                        <el-button @click="toEdit(row)" v-else type="primary" size="small" icon="Plus"></el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120px">
                    <template #="{ $index }">
                        <el-button type="primary" size="small" icon="Delete"
                            @click="saleAttr.splice($index, 1)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" size="default" @click="save"
                :disabled="saleAttr.length > 0 ? false : true">保存</el-button>
            <el-button @click="cancel" type="primary" size="default">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { reqAddOrUpdateSpu, reqAllTradeMark, reqSpuImageList, reqSpuHasSaleAttr, reqAllSaleAttr } from '@/api/product/spu/index'
import { ElMessage } from 'element-plus';
let $emit = defineEmits(['changeScene'])
// 存储已有的spu相关数据
let allTradeMark: any = ref([])
let imgList = ref([])
let saleAttr = ref<any>([])
let allSaleAttr = ref([])
// 控制图片放大对话框的显示与隐藏
let dialogVisible = ref(false)
// 存储预览图片地址
let dialogImageUrl = ref('')
// 收集还未选择的销售属性的id和属性值名字
let saleAttrAndValueName = ref('')
// 存储已有的spu对象
let SpuParams: any = ref({
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: []
})
// 取消按钮的回调，点击通知父组件切换场景
const cancel = () => {
    $emit('changeScene', { flag: 0, params: 'update' })
}
// 获取相关spu数据的方法
const initHasSpuData = async (spu: any) => {
    // 存储已有的spu对象，将来在模板当中展示
    SpuParams.value = spu
    // 获取全部品牌的数据
    let result = await reqAllTradeMark()
    // 获取某一个产品下面的全部售卖商品照片数据
    let result1 = await reqSpuImageList(spu.id)
    // 获取已有的spu销售属性
    let result2 = await reqSpuHasSaleAttr(spu.id)
    // 获取已有的spu全部销售属性
    let result3 = await reqAllSaleAttr()

    allTradeMark.value = result.data
    imgList.value = result1.data.map((item: any) => {
        return {
            name: item.imgName,
            url: item.imgUrl
        }
    })
    saleAttr.value = result2.data
    allSaleAttr.value = result3.data
}
// 照片墙点击预览按钮的时候触发的钩子
const handlePictureCardPreview = (file: any) => {
    dialogVisible.value = true
    dialogImageUrl.value = file.url
}
// 计算出当前spu还未拥有的销售属性
let unSelectSaleAttr: any = computed(() => {
    let unSelectArr = allSaleAttr.value.filter((item: any) => {
        return saleAttr.value.every((item1: any) => {
            return item.name != item1.saleAttrName
        })
    })
    return unSelectArr
})
// 添加属性按钮的回调
let addSaleAttr = () => {
    let [baseSaleAttrId, saleAttrName] = saleAttrAndValueName.value.split(':')
    let newSaleAttr: any = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
    }
    saleAttr.value.push(newSaleAttr)
    saleAttrAndValueName.value = ''
}
// 属性值按钮的点击事件
const toEdit = (row: any) => {
    row.flag = true
    row.saleAttrValue = ''
}
// 表单元素失去焦点的回调
const toLook = (row: any) => {
    // 整理收集的属性的id和属性的名字
    const { baseSaleAttrId, saleAttrValue } = row
    // 整理成服务器需要的属性值形式
    let newSaleAttrValue = {
        baseSaleAttrId,
        saleAttrValueName: saleAttrValue
    }
    // 非法判断
    if (saleAttrValue.trim() == '') {
        ElMessage({ type: 'error', message: '属性值不能为空' })
        return
    }
    let repeat = row.spuSaleAttrValueList.find((item: any) => {
        return item.saleAttrValueName == saleAttrValue
    })
    if (repeat) {
        ElMessage({ type: 'error', message: '属性值重复' })
        return
    }
    // 追加新的属性值对象
    row.spuSaleAttrValueList.push(newSaleAttrValue)
    // 切换为查看模式
    row.flag = false
}
// 保存按钮的回调
const save = async () => {
    // 整理照片墙数据
    SpuParams.value.spuImageList = imgList.value.map((item: any) => {
        return {
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url
        }
    })
    // 整理销售属性数据
    SpuParams.value.spuSaleAttrList = saleAttr.value
    console.log(SpuParams.value);
    let result = await reqAddOrUpdateSpu(SpuParams.value)
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: SpuParams.value.id ? '更新成功' : '添加成功'
        })
        // 通知父组件切换场景为0
        $emit('changeScene', { flag: 0, params: SpuParams.value.id ? 'update' : 'add' })
    } else {
        ElMessage({
            type: 'error',
            message: SpuParams.value.id ? '更新失败' : '添加失败'
        })
    }

}

// 添加一个新的spu初始化请求的方法
const initAddSpu = async (c3Id: any) => {
    // 清空数据
    Object.assign(SpuParams.value, {
        category3Id: '',
        spuName: '',
        description: '',
        tmId: '',
        spuImageList: [],
        spuSaleAttrList: []
    })
    imgList.value = []
    saleAttr.value = []
    saleAttrAndValueName.value = ''
    // 存储三级分类id
    SpuParams.value.category3Id = c3Id
    // 获取全部品牌的数据
    let result = await reqAllTradeMark()
    // 获取已有的spu全部销售属性
    let result1 = await reqAllSaleAttr()
    allTradeMark.value = result.data
    allSaleAttr.value = result1.data
}
// 对外暴露子组件的initHasSpuData方法
defineExpose({ initHasSpuData, initAddSpu })
</script>

<style scoped></style>